package Jogo.Comm {
	import Jogo.States.PhaseState;
	import Jogo.Util;
	
	import flash.events.Event;
	import flash.events.ProgressEvent;
	import flash.events.ServerSocketConnectEvent;
	import flash.net.ServerSocket;
	import flash.net.Socket;
	import flash.system.System;
	import flash.utils.ByteArray;
	
	import mx.controls.Alert;
	
	public class FlashSocket {
		/* The port to connect to the framework */
		private const PORT : int = 7070;
		/* The IP to conncet to the framework */
		private static const HOST_IP : String = "127.0.0.1";
		
		/* Socket to communicate with the middleware */
		private static var sckt : Socket;
		
		private static var thisIp : String;
		
		public static var instance : FlashSocket = null; 
		
		public static function getInstance():FlashSocket{
			if (instance == null){
				new FlashSocket();
			}
			
			return instance;
		}
		
		public function FlashSocket(){
			instance = this;
			sckt  = new Socket();
			
			try{
				sckt = new Socket(HOST_IP, PORT);
			} catch (err:Error){
				trace("Couldn't connect to the Framework socket.");
				trace(err.getStackTrace());
				System.exit(0);
			}
			
			sckt.addEventListener(Event.CONNECT, onConnect);	
			sckt.addEventListener(Event.CLOSE, onClose);
		}
		
		/* This socket has succesfully connected to the middleware */
		private function onConnect(e:Event) : void{
			sckt.addEventListener(ProgressEvent.SOCKET_DATA, onDataReceive);
			thisIp = new String(sckt.localAddress);
		}
		
		private function onClose(ev:Event) : void{
			PhaseState.destroy();
			
		}
		
		private function onDataReceive(e:ProgressEvent) : void{
			var ba : ByteArray = new ByteArray();
			
			try {
				sckt.readBytes(ba);	
			} catch (err : Error){
				trace("Couldn't read the message from the Framework.");
				trace(err.getStackTrace());
			}
			trace(new String(ba));
			
				
			MsgHandler.receiveMessage(ba);
		}
		
		public static function getThisIp():String{
			return thisIp;
		}
		
		public static function send(msg:String):void{
			var bArray : ByteArray = new ByteArray();
			
			trace("Sending message:\n"+msg);
			
			try{
				bArray.writeUTFBytes(msg);
				sckt.writeBytes(bArray, 0, 0);
				sckt.flush();
			} catch (err : Error){
				trace("Couldn't send message to the Framework.");
				trace(err.getStackTrace());
			}
		}
	}
}